package com.ruoyi.business.controller;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.business.Dto.BusGradeTeacherDto;
import com.ruoyi.business.domain.BusGrade;
import com.ruoyi.business.domain.BusGradeTeacher;
import com.ruoyi.business.domain.BusSemester;
import com.ruoyi.business.domain.SubjectTeacher;
import com.ruoyi.business.mapper.BusGradeMapper;
import com.ruoyi.business.mapper.BusGradeTeacherMapper;
import com.ruoyi.business.mapper.BusSemesterMapper;
import com.ruoyi.business.service.IBusGradeTeacherService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.security.context.UserContext;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.*;

/**
 * 班级教师Controller
 * 
 * @author ruoyi
 * @date 2022-10-22
 */
@RestController
@RequestMapping("/business/gradeTeacher")
public class BusGradeTeacherController extends BaseController
{
    @Autowired
    private IBusGradeTeacherService busGradeTeacherService;
    //学期学年表
    @Autowired
    private BusSemesterMapper busSemesterMapper;
    //班级表
    @Autowired
    private BusGradeMapper busGradeMapper;

    //班级教师表
    @Autowired
    private BusGradeTeacherMapper busGradeTeacherMapper;

    //岗位信息表
    @Autowired
    private SysPostMapper postMapper;
    //用户表
    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private ISysUserService sysUserService;


    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPostMapper sysPostMapper;


    /**
     * 这个对应科目的所有老师信息
     * @return
     */
    @GetMapping("/postTeachers")
    public AjaxResult getpostTeachers(){
        Map<String, List<String>> postTeachers = busGradeTeacherService.getPostTeachers();
        return AjaxResult.success(postTeachers);
    }



    /**
     * 接口预测试
     * 教师管理
     * 查询班级教师列表
     * 分页
     */
//    @PreAuthorize("@ss.hasPermi('system:teacher:list2')")
    @GetMapping("/list2")
    public TableDataInfo list2(int pageNum,int pageSize)
    {
        List<BusGradeTeacherDto> list = busGradeTeacherService.selectBusGradeTeacherDto();
        //结果集
        int size = list.size();
        //解析分页参数
        if (pageSize > size) {
            pageSize = size;
        }
        // 求出最大页数，防止currentPage越界
        int maxPage = size % pageSize == 0 ? size / pageSize : size / pageSize + 1;
        if (pageNum > maxPage) {
            pageNum = maxPage;
        }
        // 当前页第一条数据的下标
        int curIdx = pageNum > 1 ? (pageNum - 1) * pageSize : 0;
        // 将当前页的数据放进busGradeTeacherDtos
        List<BusGradeTeacherDto> busGradeTeacherDtos=new ArrayList<>();
        for (int i = 0; i < pageSize && curIdx + i < size; i++) {
            busGradeTeacherDtos.add(list.get(curIdx + i));
        }
        //分页
//        List<BusGradeTeacherDto> busGradeTeacherDtos = list.subList(pageNum, pageSize);
//        System.out.println(busGradeTeacherDtos.size());
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setTotal(size);
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setRows(busGradeTeacherDtos);
        tableDataInfo.setMsg("查询成功");
        return tableDataInfo;
    }
    /**
     * 删除教师记录
     */
    @DeleteMapping("/remove")
    public AjaxResult removeTeacher(Long userId){
        boolean flag = busGradeTeacherService.removeBusGradeTeacherDto(userId);
        return toAjax(flag);
    }
    /**
     * 查询班级教师列表
     */
    @PreAuthorize("@ss.hasPermi('BusGradeTeacher:gradeTeacher:list')")
    @GetMapping("/list")
    public TableDataInfo list(BusGradeTeacher busGradeTeacher)
    {
        startPage();
        List<BusGradeTeacher> list = busGradeTeacherService.selectBusGradeTeacherList(busGradeTeacher);
        return getDataTable(list);
    }
    /**
     * 教师获取所教班级
     */
    @GetMapping("/getGrade")
    public JSONObject getGradeByUserId(){
        return busGradeTeacherService.getGradeByUserId(UserContext.getUserId());
    }
    /**
     * 导出班级教师列表
     */
    @PreAuthorize("@ss.hasPermi('BusGradeTeacher:gradeTeacher:export')")
    @Log(title = "班级教师", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BusGradeTeacher busGradeTeacher)
    {
        List<BusGradeTeacher> list = busGradeTeacherService.selectBusGradeTeacherList(busGradeTeacher);
        ExcelUtil<BusGradeTeacher> util = new ExcelUtil<BusGradeTeacher>(BusGradeTeacher.class);
        util.exportExcel(response, list, "班级教师数据");
    }

    /**
     * 获取班级教师详细信息
     */
    @PreAuthorize("@ss.hasPermi('BusGradeTeacher:gradeTeacher:query')")
    @GetMapping(value = "/{gradeId}")
    public AjaxResult getInfo(@PathVariable("gradeId") Long gradeId)
    {
        return AjaxResult.success(busGradeTeacherService.
                        selectBusGradeTeacherByGradeId(gradeId));
    }

    /**
     * 新增班级教师
     */
    @PreAuthorize("@ss.hasPermi('BusGradeTeacher:gradeTeacher:add')")
    @Log(title = "班级教师", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BusGradeTeacher busGradeTeacher)
    {
        return toAjax(busGradeTeacherService.insertBusGradeTeacher(busGradeTeacher));
    }

    /**
     * 修改班级教师
     */
    @PreAuthorize("@ss.hasPermi('BusGradeTeacher:gradeTeacher:edit')")
    @Log(title = "班级教师", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BusGradeTeacher busGradeTeacher) throws SQLIntegrityConstraintViolationException {
        return toAjax(busGradeTeacherService.updateBusGradeTeacher(busGradeTeacher));
    }

    /**
     * 删除班级教师
     */
    @PreAuthorize("@ss.hasPermi('BusGradeTeacher:gradeTeacher:remove')")
    @Log(title = "班级教师", businessType = BusinessType.DELETE)
	@DeleteMapping("/{gradeIds}")
    public AjaxResult remove(@PathVariable Long[] gradeIds)
    {
        return toAjax(busGradeTeacherService.deleteBusGradeTeacherByGradeIds(gradeIds));
    }



    @GetMapping("/getAllTeacher")
    public AjaxResult TeacherGradeGallery() {


        Long teacherid = UserContext.getUserId();


        //封装查询学期学年表中的当年学期的学期id的map
        HashMap<String, Long> hashMap = new HashMap<>();
        //反向封装查询学期学年表中的当年学期的学期id的map
        HashMap<Long, String> hashMap1 = new HashMap<>();
        //封装班级表中的班级id和班级名
        HashMap<Long, String> hashMap2 = new HashMap<>();
        //封装班级id和岗位id
        HashMap<String,String> hashMap3 = new HashMap<>();
        //封装班级id和
        //查询学期学年表中的当年学期的学期id
        QueryWrapper<BusSemester> sqw = new QueryWrapper<>();
        sqw.eq("semester_now", "1").select("semester_id", "semester_name", "semester_year");

        List<BusSemester> busSemesters = busSemesterMapper.selectList(sqw);
        for (BusSemester busSemester : busSemesters) {
            Long semesterId = busSemester.getSemesterId();
            String semesterName = busSemester.getSemesterName();
            String semesterYear = String.valueOf(busSemester.getSemesterYear());
            hashMap.put(semesterYear + semesterName, semesterId);
            hashMap1.put(semesterId, semesterYear + semesterName);

        }

        //查询班级表中的学期id和班主任的id为指定的数据时返回班级id
        Set<Long> longs = hashMap1.keySet();
        for (Long aLong : longs) {
            //根据班级表中的学年学期的id，还有班主任的id对应上，查询班级的id
            QueryWrapper<BusGrade> gqw = new QueryWrapper<>();
            gqw.eq("semester_id", aLong)
                    .eq("user_id", 1597409114416234L)
                    .select("grade_id", "grade_name");
            List<BusGrade> busGrades = busGradeMapper.selectList(gqw);
            //遍历班级的信息。
            for (BusGrade busGrade : busGrades) {
                Long gradeId = busGrade.getGradeId();
                String gradeName = busGrade.getGradeName();
                //将班级的id和班级的名字封装在map中
                hashMap2.put(gradeId, gradeName);
                //根据在遍历的班级id到班级教师表中去查询班级的id、岗位id、用户id
                QueryWrapper<BusGradeTeacher> tqw = new QueryWrapper<>();
                tqw.eq("grade_id",gradeId).select("grade_id","post_id","user_id");
                List<BusGradeTeacher> busGradeTeachers = busGradeTeacherMapper.selectList(tqw);
                //从中遍历班级教师表的信息
                for (BusGradeTeacher busGradeTeacher : busGradeTeachers) {
                    //查询班级的id，并转型成String
                    Long gradeId1 = busGradeTeacher.getGradeId();
                    String s = String.valueOf(gradeId1);

                    Long userId = busGradeTeacher.getUserId();

                    Long postId = busGradeTeacher.getPostId();
                    //根据遍历的岗位的id到，岗位表中去读取岗位的名字
                    SysPost sysPost = postMapper.selectPostById(postId);
                    String postName = sysPost.getPostName();

                    //有一些的岗位是没有老师的（例如一年级只有语文数学，没有科学的任课老师）
                    //所以将一些有有课的老师的名字封装到map中
                    if(userId!=null){
                        SysUser sysUser = sysUserMapper.selectUserById(userId);
                        String nickName = sysUser.getNickName();
                        hashMap3.put(s+postName,nickName);
                        //这个课没有任课老师的，封装其他的信息
                    }else {
                        hashMap3.put(s+postName,"没有该任课老师");
                    }


                }

            }

        }

        return AjaxResult.success(hashMap3);
    }


    @GetMapping("/myInfo")
    public AjaxResult getGrowthCount() {
        Long userId = UserContext.getUserId();
        HashMap<String,Long> hashMap= new HashMap<>();
        HashMap<Long,Object> hashMap1 = new HashMap<>();
        QueryWrapper<BusGradeTeacher> tqw = new QueryWrapper<>();
        tqw.eq("user_id",userId).select("user_id","post_id","grade_id");
        List<BusGradeTeacher> busGradeTeachers = busGradeTeacherMapper.selectList(tqw);
        for (BusGradeTeacher busGradeTeacher : busGradeTeachers) {
            Long userId1 = busGradeTeacher.getUserId();
            Long postId = busGradeTeacher.getPostId();
            Long gradeId = busGradeTeacher.getGradeId();
            String s = String.valueOf(gradeId);
            if (userId1!=null){
                SysPost sysPost = sysPostMapper.selectPostById(postId);
                String postName = sysPost.getPostName();
                hashMap.put(s+postName,postId);
            }
        }
        hashMap1.put(userId,new ArrayList<SysUser>());

        SysUser sysUser = sysUserMapper.selectUserById(userId);
        String nickName = sysUser.getNickName();
        String phonenumber = sysUser.getPhonenumber();
        String avatar = sysUser.getAvatar();
        List list = (List) hashMap1.get(userId);

        list.add(nickName);
        list.add(phonenumber);
        list.add(avatar);

        Set<String> strings = hashMap.keySet();
        for (String string : strings) {
            list.add(string);
        }

        return AjaxResult.success(hashMap1);
    }

    @GetMapping("/getGradeTeacher/{gradeId}")
    public AjaxResult getGradeTeacher(@PathVariable Long gradeId){
        List<SubjectTeacher> teachers = busGradeTeacherService.
                getGradeTeacher(gradeId);
        return AjaxResult.success(teachers);
    }
    //获取班主任所带班级
    @GetMapping("/getLeadGrade")
    public AjaxResult getLeadGrade(){
        Long userId = SecurityUtils.getUserId();
        return AjaxResult.success(busGradeTeacherService.getLeadGrade(userId));
    }
}
